﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using LunwenYun.Infrastructure.Entities.Entity;
using LunwenYun.Tool.Framework;

namespace LunwenYun.Portal.WebLogic
{
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CompleteAgentInfoAttribute : AuthorizeAttribute
    {
        protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
        {
            if (!httpContext.User.Identity.IsAuthenticated)
            {
                return false;
            }
            var user = new User().Find(httpContext.User.Identity.Name);
            if (user == null || 
                user.SystemRole != Infrastructure.Entities.Enum.UserRole.PaperAgent ||
                !user.IsActivate ||
                !user.IsComplete ||
                user.IsRefuse)
            {
                return false;
            }
            return true;
        }

        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            string url = System.Web.HttpContext.Current.Request.RawUrl;
            string ToUrl = string.Empty;
            if (!filterContext.HttpContext.User.Identity.IsAuthenticated)
            {
                ToUrl = "/account/login?returnurl=" + System.Web.HttpContext.Current.Server.UrlEncode(url);
            }
            else
            {
                var user = new User().Find(filterContext.HttpContext.User.Identity.Name);
                if (user.SystemRole != Infrastructure.Entities.Enum.UserRole.PaperAgent ||
                    user.IsRefuse)
                {
                    ToUrl = "/home/forbidden";
                }
                if (!user.IsActivate)
                {
                    ToUrl = "/account/beactivate?n=" + EncodeByBase64.Encode(filterContext.HttpContext.User.Identity.Name);
                }
                if (!user.IsComplete)
                {
                    ToUrl = "/home/setagentinfo";
                }
            }
            filterContext.Result = new RedirectResult(ToUrl);
        }
    }
}
